package ferp.poll;

import java.util.LinkedList;
import java.util.List;

/**
 * User: olegs
 * Date: 11/05/2014 10:10
 */
public class Poll
{
  public static abstract class Language
  {
    public abstract String title();
    public abstract String description();
    public abstract String bonus();

    public String question(int id) {return questions()[id];}
    public String option(int question, int option) {return options()[question][option];}

    protected abstract String[] questions();
    protected abstract String[][] options();
  }

  public static interface Factory
  {
    Poll create(long id, Poll.Language language);
  }

  public static class Bonus
  {
    public Bonus(int value, String description)
    {
      this.description = description;
      this.value = value;
    }

    public int value() {return value;}
    public String description() {return description;}

    private int value;
    private String description;
  }

  public static final String REFUSED = "x";

  public Poll(long id, Language language, int bonus, Question question)
  {
    this.id = id;
    this.title = language.title();
    this.description = language.description();
    this.bonus = new Bonus(bonus, language.bonus());
    this.question = question;
  }

  public long id() {return id;}
  public String title() {return title;}
  public String description() {return description;}
  public Bonus bonus() {return bonus;}
  //public Question question() {return question;}

  // get to specific question by previous answers
  // answers must be null if poll has not started yet
  public Question question(String answers)
  {
    if (answers == null)
      return null;

    Question q = question;

    for (char a : answers.toCharArray())
    {
      Option o = q.option(a - '0');

      if (o == null || o.next() == null)
        return null;

      q = o.next();
    }

    return q;
  }

  public List<String> keys()
  {
    LinkedList<String> list = new LinkedList<String>();
    String path = "";

    keys(question, path, list);

    // add predefined refusal key
    list.add(REFUSED);

    return list;
  }

  private long id;
  // poll title
  private String title;
  // general description
  private String description;
  // bonus in days of ADless play
  private Bonus bonus;
  // first question
  private Question question;

  private void keys(Question question, String path, List<String> keys)
  {
    if (question == null)
    {
      keys.add(path);

      return;
    }

    int i = 0;

    for (Option option : question.options())
      keys(option.next(), path + (i++), keys);
  }
}
